from common.models.statistics import StatDailySite
from common.libs.Helper import ops_render
from common.libs.Helper import getFormatDate
from flask import Blueprint
from application import app
import datetime

route_index = Blueprint('index_page', __name__)

@route_index.route('/')
def index():
    # 初始化数据格式
    resp_data = {
        'data': {
            'finance': {
                'today': 0,
                'month_total': 0,
            },
            'order': {
                'today': 0,
                'month_total': 0,
            },
            'member': {
                'total': 0,
                'new_today': 0,
                'month_total': 0,
            },
            'share': {
                'today': 0,
                'month_total': 0,
            }
        }
    }
    now_date = datetime.datetime.now()
    before_date = now_date - datetime.timedelta(days=30)
    date_from = getFormatDate(before_date, format='%Y-%m-%d')
    date_to = getFormatDate(now_date, format='%Y-%m-%d')

    daily_item_list = StatDailySite.query.filter(StatDailySite.date >= date_from, StatDailySite.date <= date_to) \
        .order_by(StatDailySite.id.asc()).all()

    if daily_item_list:

        for item in daily_item_list:
            resp_data['data']['finance']['month_total'] += item.total_pay_money
            resp_data['data']['order']['month_total'] += item.total_order_count
            resp_data['data']['member']['month_total'] += item.total_new_member_count
            resp_data['data']['member']['total'] = item.total_member_count
            resp_data['data']['share']['month_total'] += item.total_shared_count

            if getFormatDate(item.date,format='%Y-%m-%d' ) == date_to:
                resp_data['data']['finance']['today'] = item.total_pay_money
                resp_data['data']['order']['today'] = item.total_order_count
                resp_data['data']['member']['new_today'] = item.total_new_member_count
                resp_data['data']['share']['today'] = item.total_shared_count


    return ops_render('index/index.html',resp_data)
